<!-- 创建蓝牙密码 -->
<template>
	<view class="container">
		<van-loading size="24px" vertical class="loading" type="spinner" v-if="showLoading">加载中...</van-loading>
		<view v-else>
			<view class="title">设置有效期</view>
			<view class="start_date_text">生效日期</view>
			<view class="start_lay" @click="openDatetimePicker(1)">
				<view class="input_start_date">{{starDate?starDate : "请选择生效日期"}}</view>
				<image src="../../../static/index/jiantou_down.png"></image>
			</view>

			<view class="start_date_text">失效日期</view>
			<view class="start_lay" @click="openDatetimePicker(0)">
				<view class="input_start_date">{{endDate?endDate :"请选择失效日期"}}</view>
				<image src="../../../static/index/jiantou_down.png"></image>
			</view>
			<view class="bottom-box">
				<view class="btn" @click="createPwdFun" :class="isCreatePwd? 'disabled' : ''">
					{{isCreatePwd?createType==2?'请等待'+seconds+'秒':'正在生成':passWord?'重新创建密码':'创建密码'}}
				</view>
			</view>
			<SimpleDateTimePicker ref="myPicker" @submit="handleSubmit" :start-year="chooseStarYear" :end-year="chooseEndYear" :defaultdate="defaultdate" />
		</view>
	</view>

</template>

<script>
	import moment from '@/utils/moment.js';
	import SimpleDateTimePicker from "@/uni_modules/buuug7-simple-datetime-picker/components/buuug7-simple-datetime-picker/buuug7-simple-datetime-picker.vue";
	import util from '@/utils/util.js';
	import bleUtils from '@/utils/BleUtils.js';
	import {
		cmd21,
		cmd63
	} from '@/utils/cmd/index.js';
	import {
		getGroupWifiLockPassword,
		configGroupWifiLockPassword,
		updateSendPass
	} from '@/api/lock.js'
	export default {
		name: 'createPassword',
		data() {
			const chooseStarYear = +(moment().year());
			// console.log('chooseStarYear===>', chooseStarYear)
			const chooseEndYear = +(moment().add(20, 'y').year());
			// console.log('chooseEndYear===>', chooseEndYear)
			return {
				showLoading: true,
				lockId: '',
				lockMac: '',
				passWord: '',
				isCreatePwd: false,
				timer: null,
				userId: this.$userInfo.userId,
				showPwd: false,
				receiveBleStr: '', // 收到的蓝牙锁回复信息				
				timeOutSec: this.$sysInfo.timeOutSecs, // 超时秒数
				adminMob: '', // 管理者手机号
				adminPwd: '', // 管理者密码
				userMob: '', // 用户手机号
				userPwd: '', // 用户密码
				bleName: '', // 蓝牙名称
				formatLockMac: '', // 格式化的蓝牙mac 安卓连接用
				numPwd: '', // 蓝牙生成的数字密码
				oldNumPwd: '', // 门锁之前的数字密码
				lockDetail: '',
				createType: '', // 1:蓝牙方式  2:远程方式
				starDate: "",
				endDate: "",
				datetype: null, // 	点击开始还是结束时间
				defaultdate: '',
				chooseStarYear,
				chooseEndYear,
				seconds: 10,
			}
		},
		components: {
			SimpleDateTimePicker,
		},
		onLoad(option) {
			this.createType = +option.createType;
			// this.createType = 1;
			const lockInfo = this.lockDetail = this.$store.state.lockInfo;
			this.lockId = lockInfo.lockId;
			this.lockMac = lockInfo.mac.toUpperCase();
			this.adminMob = lockInfo.ownedInfo.managerMobile || '';
			this.adminPwd = lockInfo.ownedInfo.managerPassword || '';
			this.userMob = this.$userInfo.mobile || '';
			this.userPwd = this.adminPwd || '';
			this.bleName = lockInfo.bleName ? (lockInfo.bleName + '').toUpperCase() : '0905' + this.lockMac;
			console.log('lockInfo===>', lockInfo)
			if (this.lockMac) {
				this.formatLockMac = util.strInsert(this.lockMac, 2);
			}
			setTimeout(() => {
				this.showLoading = false;
			}, 800)
		},
		onUnload() {
			if (this.timer) clearInterval(this.timer)
		},
		methods: {
			async createBLPassword() { // 蓝牙创建密码
				try {
					const startSec = moment(this.starDate).unix(); // 时间戳 秒
					const endSec = moment(this.endDate).unix(); // 时间戳 秒
					this.receiveBleStr = '';
					if (!this.$sysInfo.locationEnabled) {
						util.alert('请先开启手机GPS定位服务!');
						return;
					}
					if (!this.$sysInfo.locationAuthorized) {
						// 让用户授权开启定位服务 为了让老版本的安卓手机能使用蓝牙
						await bleUtils.doAuthorize('scope.userLocation')
					}
					util.loading('正在生成数字密码...');
					// 打开蓝牙扫描设备
					await bleUtils.openBluetoothAdapter();
					await bleUtils.waitBleConnAndNotify(this.bleName, this.formatLockMac);
					// 如果有旧密码 那先删除旧密码
					let cmdMsg = ''
					if (this.oldNumPwd) {
						console.log('old password  -->', this.oldNumPwd);
						cmdMsg = cmd63.generate(this.adminMob, this.adminPwd, this.userMob, this.userPwd, this
							.oldNumPwd, '09'); // 删除密码
						console.log('cmd63 / optype 09 删除密码 -->', cmdMsg);
					} else {
						// 给锁发送21命令 进行校时
						cmdMsg = cmd21.generate();
						console.log('cmd21 / 校时 -->', cmdMsg);
					}
					// 监听当特征值发生变化的回调
					bleUtils.onBLECharacteristicValueChange((res) => {
						this.receiveBleData(res);
					});
					// 发送命令
					this.sendPacket(cmdMsg);
				} catch (err) {
					console.log('bluetooth err--->', err)
					util.hideLoading();
					util.infotip(err.errCode);
					// 关闭蓝牙连接
					bleUtils.closeBLEConnection();
				}
			},
			// 发送数据包给蓝牙设备
			async sendPacket(cmdMsg) {
				try {
					const cmdData = bleUtils.myStringtoHex(cmdMsg);
					const unit8Array_data = new Uint8Array(cmdData);
					const data = unit8Array_data.buffer;
					await bleUtils.writeBLECharacteristicValue(data);
					this.timer = setTimeout(() => {
						clearTimeout(this.timer);
						util.hideLoading();
						util.alert('命令下发超时,请确保锁处于唤醒状态!')
						bleUtils.closeBLEConnection();
					}, this.timeOutSec)
				} catch (err) {
					util.hideLoading();
					util.infotip(err.errCode);
					// 关闭蓝牙连接
					bleUtils.closeBLEConnection();
				}
			},
			async receiveBleData(res) {
				try {
					if (this.timer) clearTimeout(this.timer);
					console.log('receive bluetooth data--->', res);
					const data = res.substring(24, res.length - 2);
					// console.log('receive pack data--->', data);
					const cmdWord = data.substr(0, 2);
					if (cmdWord == '11') { // 校时的返回 接下来 设置新密码
						this.oldNumPwd = '';
						// 设置新的数字密码
						this.numPwd = util.createUUID(6, 10);
						let startSec = +(moment(this.starDate).unix()); // 密码有效时间 开始时间戳 秒
						let endSec = +(moment(this.endDate).unix()); // 密码有效时间 结束时间戳 秒			
						startSec = util.padLeft(startSec.toString(16), '0', 10);
						endSec = util.padLeft(endSec.toString(16), '0', 10);
						console.log('pwd-->', this.numPwd, ' startSec-->', startSec, ' endSec-->', endSec);
						const cmdMsg = cmd63.generate(this.adminMob, this.adminPwd, this.userMob, this.userPwd, this
							.numPwd, '07', startSec, endSec);
						console.log('cmd63 / optype 07 新增密码 -->', cmdMsg);
						// 发送命令
						this.sendPacket(cmdMsg);
					}
					if (cmdWord == '53') { // 53命令的返回有两种情况 一种是删除密码 一种是重新设置密码
						const resCode = data.substr(2, 2);
						console.log('receive cmdWord--->', cmdWord, ' resCode--->', resCode);
						if (resCode != '01') { // 表示失败
							util.hideLoading();
							const errMsg = '添加数字密码失败,请确保锁处于激活状态!';
							// 关闭蓝牙连接
							bleUtils.closeBLEConnection();
							util.alert(errMsg);
							return;
						}
						if (this.oldNumPwd) {
							this.oldNumPwd = '';
							// 发送校时命令
							const cmdMsg = cmd21.generate();
							console.log('cmd21 / 校时 -->', cmdMsg);
							// 发送命令
							this.sendPacket(cmdMsg);
						} else {
							this.sendPwdBackend(this.numPwd);
							// 关闭蓝牙连接
							bleUtils.closeBLEConnection();
						}
					}
				} catch (err) {
					console.log('receiveBleData err-->', err);
					util.hideLoading();
					// 关闭蓝牙连接
					bleUtils.closeBLEConnection();
				}
			},
			// 将密码发送给后台
			async sendPwdBackend(numPassword = '') {
				try {
					const param = {
						lockId: this.lockId,
						ownerId: this.userId,
						creatType: 1, // 1:蓝牙  2:远程创建密码
						numPassword,
						startTime: this.starDate,
						endTime: this.endDate
					}
					this.isCreatePwd = true;
					const res = await configGroupWifiLockPassword(param);
					util.hideLoading();
					if (res.statecode == 0) {
						const code = res.data.code + '';
						console.log('code------->', code)
						if (code == 'true') {
							util.alert('数字密码创建成功!');
							this.timer = setTimeout(() => {
								this.isCreatePwd = false;
								clearTimeout(this.timer);
								uni.navigateBack({
									delta: 2
								})
							}, 2000)
						} else {
							uni.showToast({
								title: res.statemsg + ' 请重新生成',
								icon: "none",
								mask: true,
							})
						}
					} else {
						this.isCreatePwd = false;
						uni.showToast({
							title: res.statemsg,
							icon: "none",
							mask: true,
						})
						return;
					}
				} catch (err) {
					util.hideLoading();
					this.isCreatePwd = false;
					console.log('configGroupWifiLockPassword err', err)
				}
			},
			// 创建远程密码
			async createOLPassword(numPassword = '', type = 2) {
				try {
					const param = {
						lockId: this.lockId,
						ownerId: this.userId,
						creatType: type,
						numPassword,
						startTime: this.starDate,
						endTime: this.endDate
					}
					this.isCreatePwd = true;
					const res = await configGroupWifiLockPassword(param);
					if (res.statecode == 0) {
						const code = res.data.code + '';
						console.log('code------->', code)
						if (type == 2 && code == 1000006) { // 远程方式						
							this.timer = setInterval(() => {
								if (this.seconds > 0) {
									this.seconds--;
									return;
								}
								if (this.timer) clearInterval(this.timer);
								this.isCreatePwd = false;
								uni.navigateBack({
									delta: 1
								})
							}, 1000)
							return;
						}
						this.isCreatePwd = false;
						util.hideLoading();
						if (code == 'true') {
							util.alert('远程密码创建成功!');
							uni.navigateBack({
								delta: 1
							})
						} else {
							uni.showToast({
								title: res.statemsg,
								icon: "none",
								mask: true,
							})
						}
					} else {
						this.isCreatePwd = false;
						uni.showToast({
							title: res.statemsg,
							icon: "none",
							mask: true,
						})
					}
				} catch (err) {
					this.isCreatePwd = false;
					console.log('configGroupWifiLockPassword err', err)
				}
			},
			// 打开picker
			openDatetimePicker(type) {
				uni.hideKeyboard()
				this.datetype = type
				if (this.datetype == 1) { //选择开始时间					
					// this.defaultdate = moment().format('YYYY-MM-DD HH:mm:SS') //this.starDate 
					this.defaultdate = moment().format('YYYY-MM-DD HH:mm:ss') //this.starDate
					console.log('defaultdate==========>',this.defaultdate)
				} else {
					this.defaultdate = this.endDate
				}
				this.$refs.myPicker.show();
			},
			// 关闭picker
			closeDatetimePicker() {
				this.$refs.myPicker.hide();
			},
			handleSubmit(e) {
				// {year: "2019", month: "07", day: "17", hour: "15", minute: "21"}
				console.log(e, '选择日期');
				let date = `${e.year}-${e.month}-${e.day} ${e.hour}:${e.minute}:00`;
				console.log(date)
				if (this.datetype == 1) { //选择开始时间
					if (this.endDate && moment(date).isBefore(this.endDate)) {
						util.toast("开始时间必须小于结束时间")
						return
					}
					this.starDate = date
				} else {
					if (this.starDate && moment(date).isBefore(this.starDate)) {
						util.toast("结束时间必须大于开始时间")
						return
					}
					if (!this.starDate) {
						util.toast("请先选择开始时间")
						return
					}
					this.endDate = date
				}
			},
			async createPwdFun() {
				if (this.starDate.length == 0) {
					util.toast("请选择生效日期")
					return
				}
				if (this.endDate.length == 0) {
					util.toast("请选择失效日期")
					return
				}
				// 先获取老密码吧				
				const res = await getGroupWifiLockPassword({
					lockMac: this.lockMac,
					createType: 1
				});
				if (res.statecode != 0) {
					uni.showToast({
						title: '获取旧密码失败,请联系后台!',
						icon: "none",
						mask: true,
					})
					return;
				}
				this.oldNumPwd = res.data.password || ''
				if (this.createType == 1) {
					this.createBLPassword(); // 创建蓝牙密码
				} else {
					this.createOLPassword(); // 创建远程密码
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {

		background-color: white;

		.loading {
			margin: 50% auto;
		}

		.disabled {
			pointer-events: none;
			cursor: default;
			opacity: 0.6;
		}

		.top_root {
			padding-right: 32rpx;
			padding-left: 32rpx;
			height: 80rpx;
			align-items: center;
			background-color: #E2EEFF;
			display: flex;

			view {
				margin-left: 26rpx;
				flex: 1;
			}

			image {
				width: 32rpx;
				height: 32rpx;

			}
		}

		.title {
			margin-top: 80rpx;
			margin-left: 32rpx;
			margin-bottom: 40rpx;
			font-size: 32rpx;
			font-weight: bold;
			color: #1F2642;
		}

		.start_date_text {
			margin-left: 32rpx;
			height: 40rpx;
			font-size: 28rpx;
			color: #62677A;
			line-height: 40px;
		}

		.start_lay {
			position: relative;
			margin-top: 40rpx;

			.input_start_date {
				flex: 1;
				margin-left: 32rpx;
				padding-left: 32rpx;
				line-height: 88rpx;
				padding-right: 32rpx;
				max-lines: 1;
				margin-right: 32rpx;
				height: 88rpx;
				color: #BBBDC6;
				background-color: #F8F8FA;
				border-radius: 10px;
			}

			:nth-child(2) {
				width: 36rpx;
				height: 36rpx;
				position: absolute;
				right: 60rpx;
				top: 30rpx;
				justify-content: center;
			}
		}

		.bottom-box {
			position: absolute;
			bottom: 50rpx;
			text-align: center;
			width: 100%;

			.btn {
				width: 85%;
				font-size: 35rpx;
				padding: 22rpx;
				text-align: center;
				background: linear-gradient(135deg, #4593FF 0%, #1C78F7 100%);
				color: #fff;
				border-radius: 20rpx;
				margin: 0 auto;
			}

			.text {
				width: 85%;
				font-size: 24rpx;
				color: #8F92A0;
				margin: 20rpx;
			}
		}

		.picker-view {
			width: 750rpx;
			height: 600rpx;
			margin-top: 20rpx;
		}

		.item {
			height: 50px;
			align-items: center;
			justify-content: center;
			text-align: center;
		}
	}
</style>